<template>
  <div class="page-container user-container">
    <div class="handle-box">
      <span style="padding:8px;font-size:13px;">用户账号/姓名：</span>
      <el-input v-model="query.Keyword" placeholder="用户账号/姓名" class="handle-input mr10"></el-input>
      <span style="padding:8px;"></span>
      <el-checkbox v-model="userSoureCheck">显示鸿路系统用户</el-checkbox>
      <span style="padding:8px;"></span>
      <el-button size="small" type="success" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button size="small" type="warning" icon="el-icon-refresh-left" @click="reset">重置</el-button>
    </div>
    <div class="handle-box">
      <el-button type="primary" icon="el-icon-document-add" size="small" @click="createBus()">新建</el-button>
      <el-button type="danger" icon="el-icon-delete" size="small" @click="delAllSelection">批量删除</el-button>
    </div>
    <el-table :data="tableData" height="80vh" border class="table" ref="multipleTable" header-cell-class-name="table-header" v-loading="tableLogin" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" :selectable='isDisabled' fixed="left"></el-table-column>
      <el-table-column prop="name" label="ID" align="center">
        <template slot-scope="scope">{{scope.row.id}}</template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="scope">{{scope.row.name}}</template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="scope">{{scope.row.mobile}}</template>
      </el-table-column>
      <el-table-column prop="address" label="邮箱" align="center">
        <template slot-scope="scope">{{scope.row.email}}</template>
      </el-table-column>
      <el-table-column prop="address" label="组织" align="center">
        <template slot-scope="scope">{{scope.row.org_name}}</template>
      </el-table-column>
      <el-table-column prop="address" label="创建时间" align="center">
        <template slot-scope="scope">{{scope.row.update_time}}</template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-if="scope.row.userSoure!=0">
            编辑
          </el-button>
          <el-button type="text" icon="el-icon-delete" class="red" style="color:#F56C6C !important;" v-if="scope.row.userSoure!=0" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination layout="sizes,total, prev, pager, next, jumper" :current-page="query.PageNumber" :page-size="query.PageSize" :page-sizes="[10,20, 50, 100, 150, 200]" @size-change="handleSizeChange" :total="total" @current-change="handleCurrentChange"></el-pagination>
    </div>
  <!--添加管理员-->
  <el-dialog :title="adminTitle" :visible.sync="editVisible" width="60%">
    <div class="list-group">
      <el-row :gutter="20">
        <el-col :span="3">
          <div class="list-title"><span class="mast-icon">*</span>{{modelList.account.name}}:</div>
        </el-col>
        <el-col :span="9">
          <el-input v-model.trim="modelList.account.value" :placeholder="modelList.account.placeholder"></el-input>
          <p style="color:red;padding:6px 0;font-size:12px;">账号长度不能小于8位</p>
        </el-col>
        <el-col :span="3">
          <div class="list-title">{{modelList.password.name}}:</div>
        </el-col>
        <el-col :span="9">
          <el-input type="password" v-model.trim="modelList.password.value" :placeholder="modelList.password.placeholder"></el-input>
          <p style="color:red;padding:6px 0;font-size:12px;" v-if="addOrEdit == 1">不填写默认密码：123456,最小长度6位</p>
          <p style="color:red;padding:6px 0;font-size:12px;" v-else>最小长度6位</p>
        </el-col>
      </el-row>
    </div>
    <div class="list-group">
      <el-row :gutter="20">
        <el-col :span="3">
          <div class="list-title"><span class="mast-icon">*</span>{{modelList.realname.name}}:</div>
        </el-col>
        <el-col :span="9">
          <el-input v-model.trim="modelList.realname.value" :placeholder="modelList.realname.placeholder"></el-input>
        </el-col>
        <el-col :span="3">
          <div class="list-title"><span class="mast-icon">*</span>{{modelList.mobile.name}}:</div>
        </el-col>
        <el-col :span="9">
          <el-input v-model.trim="modelList.mobile.value" :placeholder="modelList.mobile.placeholder"></el-input>
        </el-col>
      </el-row>
    </div>
    <div class="list-group">
      <el-row :gutter="20">
        <el-col :span="3">
          <div class="list-title"><span class="mast-icon">*</span>{{modelList.email.name}}:</div>
        </el-col>
        <el-col :span="9">
          <el-input v-model.trim="modelList.email.value" :placeholder="modelList.email.placeholder"></el-input>
        </el-col>
      </el-row>
    </div>
    <div class="list-group">
      <el-row :gutter="20">
        <el-col :span="3">
          <div>{{modelList.role_ids.name}}:</div>
        </el-col>
        <el-col :span="21">
          <el-checkbox-group v-model="roleListVal">
            <el-checkbox :label="val.id" @change="jsMethod()" :checked="val.active" v-for="(val,key) in roleList" :key="key">{{val.role_name}}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="editVisible = false">取 消</el-button>
      <el-button size="medium" type="primary" @click="saveEdit">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
  name: 'admin',
  data() {
    return {
      adminTitle: '',
      orangeTitle: '',
      roleListVal: [],
      organizationName: '',
      roleList: [],
      searchName: '',
      searchOrgId: '',
      roleId: '',
      tableData: [],
      adminName: '',
      editVisible: false,
      addOrEdit: 1,
      adminId: '',
      modelList: {
        account: { value: '', request: true, name: '账号', placeholder: '请输入账号', type: 'input' },
        password: { value: '', request: false, name: '密码', placeholder: '请输入密码', type: 'input' },
        realname: { value: '', request: true, name: '真实姓名', placeholder: '请输入真实姓名', type: 'input' },
        mobile: { value: '', request: true, name: '手机号', placeholder: '请输入手机号', type: 'input' },
        email: { value: '', request: true, name: '邮箱', placeholder: '请输入邮箱', type: 'input' },
        org_id: { value: '', request: true, name: '组', placeholder: '请选择组', type: 'select' },
        role_ids: { value: '', request: true, name: '角色', placeholder: '请选择角色', type: 'select' },
      },
      query:{
        PageNumber:1,
        PageSize:20,
        Keyword:'',
      },
      userSoureCheck:true,
      total: 0,
      idList: [], //选择的id数组
      tableLogin:false
    };
  },
  computed: {
    ...mapState({
      processType: state => state.app.processType
    }),
  },
  watch: {
    processType:{
      deep:true,
      handler:function(val,old){
        if(val!=old){
          this.reset();
        }
      }
    }
  },
  mounted() {
    this.initAjaxMethod();
  },
  methods: {
    reset() {
      this.query.PageNumber = 1;
      this.query.Keyword = '';
      this.userSoureCheck=true;
      this.initAjaxMethod();
    },
    mouseenter(data) {
      this.orgData.mouseenterId = data.id;
    },
    mouseleave() {
      this.orgData.mouseenterId = 0;
    },
    adminSearch(data) {
      console.log(data.id);
      this.searchOrgId = data.id;
      this.handleSearch();
    },
    // 多选操作
    handleSelectionChange(val) {
      var emptyIdList = [];
      for (var i = 0; i < val.length; i++) {
        emptyIdList.push(val[i].id);
      }
      this.idList = emptyIdList;
      console.log(this.idList);
    },

    /**下面是管理员列表method */
    createBus() {
      for (let i in this.modelList) {
        this.modelList[i].value = '';
      }
      this.addOrEdit = 1;
      this.editVisible = true;
      this.roleListVal = [];
      this.organizationName = '';
      this.modelList.org_id.value = '';
      this.adminTitle = '新建用户'
    },
    getCheckedNodes() {
      let nodes = this.$refs.org.getCheckedNodes();
      this.searchOrgId = nodes.length > 0 ? nodes[0].value : '';
    },
    //删除
    handleDelete(data) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delAjaxMethod(data.id);
        })
        .catch(() => { });
    },
    //批量删除
    delAllSelection() {
      if (this.idList.length > 0) {
        this.$confirm('此操作将永久删除选中的用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$http.post(this.$API.PERMISSION_BATCH_DEL, { ids: this.idList.join() }).then(res => {
              if (res.code == 1) {
                this.initAjaxMethod();
                this.$message({
                  type: 'success',
                  message: '批量删除成功!'
                });
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
      } else {
        this.$message({
          message: '请勾选需要删除的用户',
          type: 'warning'
        });
      }
    },
    //编辑
    handleEdit(data) {
      console.log(data);
      this.adminTitle = '编辑用户';
      this.modelList.account.value = data.account;
      this.modelList.password.value = '******';
      this.modelList.realname.value = data.realname;
      this.modelList.mobile.value = data.mobile;
      this.modelList.email.value = data.email;
      this.modelList.org_id.value = data.org_id;
      this.roleListVal = data.role.map(item => item.id);
      this.modelList.role_ids.value = this.roleListVal.join(',');
      this.organizationName = data.org_name;
      this.adminId = data.id;
      this.addOrEdit = 2;
      this.editVisible = true;
    },
    jsMethod() {
      this.modelList.role_ids.value = this.roleListVal.join(',');
    },
    //搜索
    handleSearch() {
      this.initAjaxMethod();
    },
    //组织选择
    okClick(data) {
      this.modelList.org_id.value = data.id;
      this.organizationName = data.org_name;
    },
    isDisabled(row, index) {
      if (row.userSoure == 0) {
        return false
      } else {
        return true
      }
    },
    //弹出框确定
    saveEdit() {
      if (this.addOrEdit == 1) {
        this.addAjaxMethod();
      } else {
        this.editAjaxMethod();
      }
    },
    //列表加载
    initAjaxMethod() {
      this.tableLogin=true;
      let query={
        PageNumber:this.query.PageNumber,
        PageSize:this.query.PageSize
      }
      if(this.query.Keyword){
        query.keywords=this.query.Keyword;
      }
      query.soure=1;
      if(this.userSoureCheck){
        query.soure=0;
      }
      this.$http
        .get(this.$API.USERS, query)
        .then(res => {
          this.tableLogin=false;
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.tableData = res.data.items;
            this.total = res.data.totalCount;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.tableLogin=false;
        });
    },
    //点击第几页
    handleCurrentChange(currentPage) {
      this.query.PageNumber = currentPage;
      this.initAjaxMethod();
    },
    handleSizeChange(val) {
      this.query.PageSize = val;
      this.initAjaxMethod();
    },
    //新增api
    addAjaxMethod() {
      //验证
      let test = this.testMethod();
      if (!test.flag) {
        this.$message.error(test.msg);
        return false;
      }
      const password = this.modelList.password.value;
      if (password && password.length < 6) {
        return this.$message.error('密码长度小于不能6位');
      }
      let data = {
        account: this.modelList.account.value,
        password: password,
        realname: this.modelList.realname.value,
        mobile: this.modelList.mobile.value,
        email: this.modelList.email.value,
        org_id: this.modelList.org_id.value,
        role_ids: this.modelList.role_ids.value,
      };
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.PERMISSION_ADD, data)
        .then(res => {
          loading.close();
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.$message.success('保存成功');
            this.editVisible = false;
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //删除api
    delAjaxMethod(id) {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.PERMISSION_DEL, { id: id })
        .then(res => {
          loading.close();
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.$message.success('删除成功');
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //编辑api
    editAjaxMethod() {
      //验证
      let test = this.testMethod();
      if (!test.flag) {
        this.$message.error(test.msg);
        return false;
      }
      const password = this.modelList.password.value == '******' ? '' : this.modelList.password.value;
      if (password && password.length < 6) {
        return this.$message.error('密码长度不能小于6位');
      }
      let data = {
        account: this.modelList.account.value,
        password: password,
        realname: this.modelList.realname.value,
        mobile: this.modelList.mobile.value,
        email: this.modelList.email.value,
        org_id: this.modelList.org_id.value,
        role_ids: this.modelList.role_ids.value,
        id: this.adminId,
      };
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.PERMISSION_EDIT, data)
        .then(res => {
          loading.close();
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.$message.success('编辑成功');
            this.editVisible = false;
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //组织架构
    orgAjaxMethod() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ORGANIZATION_INDEX, {})
        .then(res => {
          loading.close();
          console.log('组织列表', res);
          if (res.code == 1) {
            this.organizationData = res.data;
            this.orgData.showOrgTree = false;
            this.$nextTick(() => {
              this.orgData.showOrgTree = true;
            });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //角色列表
    roleAjaxMethod() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ROLE_INDEX, {})
        .then(res => {
          loading.close();
          console.log('角色列表', res);
          if (res.code == 1) {
            res.data.roleList.forEach(item => {
              item.active = false;
            });
            let roleList = res.data.roleList.filter(item => item.status == 1);
            this.roleList = roleList;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //验证方法
    testMethod() {
      let flag = true,
        msg = '';
      for (let i in this.modelList) {
        if (this.modelList[i].request) {
          if (i == 'mobile') {
            if (!/^1[3456789]\d{9}$/.test(this.modelList[i].value)) {
              flag = false;
              msg = '电话号码格式不正确';
              break;
            }
          } else if (i == 'email') {
            let reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
            if (!reg.test(this.modelList[i].value)) {
              flag = false;
              msg = '邮箱号码格式不正确';
              break;
            }
          } else {
            if (!this.modelList[i].value || this.modelList[i].value == '') {
              flag = false;
              msg = this.modelList[i].placeholder;
              break;
            }
          }
        }
      }
      return { flag: flag, msg: msg };
    }
  }
};
</script>

<style lang="less">
.user-container {
  .handle-input {
    width: auto;
    display: inline-block;
  }
  .list-group {
    padding: 10px 0;
  }
  .list-title {
    /* padding:7px; */
    height: 32px;
    display: flex;
    align-items: center;
  }
}
</style>